package com.gshocklab.bulkposter;

import java.util.Date;
import java.util.List;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;

import com.gshocklab.bulkposter.connection.TwitterConnectionHelper;
import com.gshocklab.bulkposter.data.DatabaseAdapter;
import com.gshocklab.bulkposter.data.dto.PostedMessage;
import com.gshocklab.bulkposter.data.dto.SocialAccount;
import com.gshocklab.bulkposter.view.AccountsActivity;
import com.gshocklab.bulkposter.view.ComposerActivity;
import com.gshocklab.bulkposter.view.adapter.PostedMessagesListAdapter;
import com.gshocklab.bulkposter.view.helper.ApplicationDialogs;
import com.gshocklab.bulkposter.view.helper.ApplicationDialogs.ISelectAccountDialogListener;

/**
 * Main application activity
 * @author vitaly gashock
 */
public class AppMainActivity extends ListActivity {
	public static final String ACCOUNT_TYPE_KEY = "accountTypeKey";
	public static final String POST_MESSAGE_KEY = "postMessageKey";
	
	public static final int APP_MAIN_ACTIVITY_RESULT_CODE = 1001;
	
	private List<SocialAccount> registeredAccounts;
	private List<PostedMessage> recentlyPosts;
	private SocialAccount currentAccount;

	private static final int MENU_POST_DETAILS = 1001;
	
	private DatabaseAdapter dbAdapter;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.main);
        setTitle(R.string.app_main_activity_title);
        registerForContextMenu(getListView());
        
        dbAdapter = new DatabaseAdapter(this);
        
        refreshRecentlyPostsList();
    }

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflanter = getMenuInflater();
		inflanter.inflate(R.menu.main_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case R.id.new_post_item :
				openComposerScreen();
				return true;
			case R.id.setup_accounts_item :
				Intent i = new Intent(this, AccountsActivity.class);
				startActivity(i);
				return true;
			default:
				return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.setHeaderTitle("Post actions");
		menu.add(0, MENU_POST_DETAILS, 0, "Post details");
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		if (item.getItemId() == MENU_POST_DETAILS) {
			AdapterView.AdapterContextMenuInfo info;
			PostedMessage post;
			
	        try {
	             info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
	             post = (PostedMessage) getListAdapter().getItem(info.position);
	             
	             ApplicationDialogs.showToast(this, post.postText);
	             
	        } catch (ClassCastException e) {
	            Log.e("BulkPoster:AccountsActivity", "bad menuInfo", e);
	            return false;
	        }
						
			return true;
		} else {
			return super.onContextItemSelected(item);
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
			case APP_MAIN_ACTIVITY_RESULT_CODE :
				if (resultCode == RESULT_OK) makePost(data);
				break;
		}
	}
	
	private void refreshRecentlyPostsList() {
		this.recentlyPosts = dbAdapter.getPostedMessages();
		
		setListAdapter(new PostedMessagesListAdapter(this, recentlyPosts));
		
		if (this.recentlyPosts.isEmpty()) {
			ApplicationDialogs.showToast(this, "There are no recently posts");
		}
	}
	
	private void openComposerScreen() {
		registeredAccounts = dbAdapter.getRegisteredAccounts();
		
		if (registeredAccounts.isEmpty()) {
			ApplicationDialogs.showToast(this, "There are no registered accounts. \nPlease register new account on Accounts screen");
			return;
		}
		
		ApplicationDialogs.showSelectAccountDialog(this, "Select account", registeredAccounts, new ISelectAccountDialogListener() {
			@Override
			public void accountSelected(SocialAccount account) {
				currentAccount = account;
				
				Intent i = new Intent(AppMainActivity.this, ComposerActivity.class);
				i.putExtra(ACCOUNT_TYPE_KEY, account.type.accountType);
				startActivityForResult(i, APP_MAIN_ACTIVITY_RESULT_CODE);
			}
		});
	}
	
	private void makePost(final Intent data) {
		// extract data from intent
		String postText = data.getStringExtra(POST_MESSAGE_KEY);
		
		if (postText.length() == 0) return;
		
		if (TwitterConnectionHelper.sendStatusUpdate(currentAccount, postText)) {
			final PostedMessage postedMessage = new PostedMessage();
			postedMessage.postingDate = new Date();
			postedMessage.postText = postText;
			postedMessage.account = currentAccount;
			
			long rowId = dbAdapter.insertPostedMessage(postedMessage);
			if (rowId > 0) {
				refreshRecentlyPostsList();
			}
		} else {
			ApplicationDialogs.showToast(this, "Error sending twitter status update");
		}
	}
}
